package com.yc.testupload.crawler.config;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 网站配置加载器
 * 负责从JSON配置文件中加载网站配置信息
 */
public class WebsiteConfigLoader {
    private static final Logger logger = LogManager.getLogger(WebsiteConfigLoader.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final String CONFIG_FILE = "website-crawler-config.json";

    /**
     * 从默认配置文件加载网站配置
     */
    public static Map<String, WebsiteConfig> loadWebsiteConfigs() {
        try (InputStream inputStream = WebsiteConfigLoader.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (inputStream == null) {
                logger.error("配置文件不存在: {}", CONFIG_FILE);
                return new HashMap<>();
            }

            JsonNode rootNode = objectMapper.readTree(inputStream);
            JsonNode websitesNode = rootNode.get("websites");
            Map<String, WebsiteConfig> websiteConfigs = new HashMap<>();

            if (websitesNode != null && websitesNode.isObject()) {
                Iterator<Map.Entry<String, JsonNode>> websiteEntries = websitesNode.fields();
                while (websiteEntries.hasNext()) {
                    Map.Entry<String, JsonNode> websiteEntry = websiteEntries.next();
                    String websiteId = websiteEntry.getKey();
                    JsonNode websiteNode = websiteEntry.getValue();

                    WebsiteConfig websiteConfig = parseWebsiteConfig(websiteNode);
                    if (websiteConfig != null) {
                        websiteConfigs.put(websiteId, websiteConfig);
                        logger.info("已加载网站配置: {}, {}", websiteId, websiteConfig.getName());
                    }
                }
            }

            logger.info("成功加载{}个网站配置", websiteConfigs.size());
            return websiteConfigs;

        } catch (IOException e) {
            logger.error("加载网站配置失败: {}", e.getMessage(), e);
            return new HashMap<>();
        }
    }

    /**
     * 解析单个网站配置
     */
    private static WebsiteConfig parseWebsiteConfig(JsonNode websiteNode) {
        try {
            String name = websiteNode.get("name").asText();
            String domain = websiteNode.get("domain").asText();
            String urlRegex = websiteNode.get("urlRegex").asText();
            JsonNode channelsNode = websiteNode.get("channels");

            Map<String, ChannelConfig> channels = new HashMap<>();
            if (channelsNode != null && channelsNode.isObject()) {
                Iterator<Map.Entry<String, JsonNode>> channelEntries = channelsNode.fields();
                while (channelEntries.hasNext()) {
                    Map.Entry<String, JsonNode> channelEntry = channelEntries.next();
                    String channelId = channelEntry.getKey();
                    JsonNode channelNode = channelEntry.getValue();

                    ChannelConfig channelConfig = parseChannelConfig(channelNode);
                    if (channelConfig != null) {
                        channels.put(channelId, channelConfig);
                    }
                }
            }

            return new WebsiteConfig(name, domain, urlRegex, channels);

        } catch (Exception e) {
            logger.error("解析网站配置失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 解析单个频道配置
     */
    private static ChannelConfig parseChannelConfig(JsonNode channelNode) {
        try {
            String id = channelNode.get("id").asText();
            String name = channelNode.get("name").asText();
            int categoryId = channelNode.get("categoryId").asInt();
            JsonNode regexPatternsNode = channelNode.get("regexPatterns");

            Map<String, String> regexPatterns = new HashMap<>();
            if (regexPatternsNode != null && regexPatternsNode.isObject()) {
                Iterator<Map.Entry<String, JsonNode>> patternEntries = regexPatternsNode.fields();
                while (patternEntries.hasNext()) {
                    Map.Entry<String, JsonNode> patternEntry = patternEntries.next();
                    String patternName = patternEntry.getKey();
                    String patternValue = patternEntry.getValue().asText();
                    regexPatterns.put(patternName, patternValue);
                }
            }

            return new ChannelConfig(id, name, categoryId, regexPatterns);

        } catch (Exception e) {
            logger.error("解析频道配置失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 测试配置文件加载
     */
    public static void main(String[] args) {
        Map<String, WebsiteConfig> configs = loadWebsiteConfigs();
        logger.info("测试加载配置文件: 共加载{}个网站配置", configs.size());
        for (Map.Entry<String, WebsiteConfig> entry : configs.entrySet()) {
            WebsiteConfig config = entry.getValue();
            logger.info("网站: {}, 频道数量: {}", config.getName(), config.getChannels().size());
        }
    }
}